package com.zjshell.pricing.price.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.zjshell.pricing.common.annotation.ControllerEndpoint;
import com.zjshell.pricing.common.controller.BaseController;
import com.zjshell.pricing.common.entity.FebsResponse;
import com.zjshell.pricing.common.entity.QueryRequest;
import com.zjshell.pricing.common.exception.FebsException;
import com.zjshell.pricing.price.entity.OilPrice;
import com.zjshell.pricing.price.service.IOilPriceService;
import com.zjshell.pricing.system.entity.User;
import com.zjshell.pricing.webservice.entity.AttachmentForm;
import com.zjshell.pricing.webservice.entity.KmReviewParamterForm;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("oilprice")
public class OilPriceController extends BaseController{
	
	@Autowired
	private IOilPriceService iOilPriceService;
	
	@GetMapping("list")
	@ControllerEndpoint(exceptionMessage = "获取价格信息失败")
    public FebsResponse oilPriceList(OilPrice oilPrice, QueryRequest request) {
        Map<String, Object> dataTable = getDataTable(this.iOilPriceService.findOilPriceDetail(oilPrice, request));
        return new FebsResponse().success().data(dataTable);
    }
	
	@PostMapping
    @RequiresPermissions("oilprice:add")
    @ControllerEndpoint(operation = "新增价格信息", exceptionMessage = "新增价格信息失败")
    public FebsResponse OilPrice(@Valid OilPrice oilPrice) throws Exception {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		System.out.println(user.getUsername());
		System.out.println(oilPrice);
		oilPrice.setAdduser(user.getUsername());
        /*String fdid = getApi(oilPrice);
        oilPrice.setFdId(fdid);*/
        this.iOilPriceService.createOilPrice(oilPrice);
        return new FebsResponse().success();
    }
	
	@GetMapping("delete/{Ids}")
    @RequiresPermissions("oilprice:delete")
    @ControllerEndpoint(operation = "删除价格信息", exceptionMessage = "删除价格信息失败")
    public FebsResponse deleteDictSites(@NotBlank(message = "{required}") @PathVariable String Ids) throws FebsException {
        String[] ids1 = Ids.split(StringPool.COMMA);
        this.iOilPriceService.deleteOilPrices(ids1);
        return new FebsResponse().success();
    }
	
	/**
	 * 创建附件对象
	 */
	AttachmentForm createAtt(String fileurl, AttachmentForm attForm) throws Exception {
		// 设置附件关键字，表单模式下为附件控件的id
		attForm.setFdKey("fd_35c3927c26cf2e");

		byte[] data = file2bytes(fileurl);
		attForm.setFdAttachment(data);

		return attForm;
	}

	/**
	 * 将文件转换为字节编码
	 */
	byte[] file2bytes(String fileName) throws Exception {
		InputStream in = new FileInputStream(fileName);
		byte[] data = new byte[in.available()];

		try {
			in.read(data);
		} finally {
			try {
				in.close();
			} catch (IOException ex) {
			}
		}

		return data;
	}
	
	public String getApi(OilPrice oilPrice) throws Exception
	{
		ResourceBundle resource = ResourceBundle.getBundle("api");
		String url = resource.getString("apiurl1");
		String loginName = resource.getString("loginname1");
		String deptid = resource.getString("depatID1");
		String oilcode = "\"92#\",";
		KmReviewParamterForm form = new KmReviewParamterForm();
		form.setFdTemplateId("1605857029887201bf7ea2842708a6a6");
		String docsubject = "据浙江发改委燃油调价" + oilPrice.getPriceText() + "执行沟通";
		form.setDocSubject(docsubject);
		form.setDocCreator("{\"LoginName\": \""+ loginName +"\"}");
		String formValues = "{\"fd_35c391bffd924c\":{\"LoginName\": \""+ loginName +"\"}, \"fd_35c391cd077fae\":\""+ deptid +"\", \"fd_35c391da35aca8\":\"2011-10-26\", \"fd_35c391fad19852\":{\"fd_35c391fad19852.fd_35c39240ef2d3c\":[\"92#\",\"95#\",\"0#\"], \"fd_35c391fad19852.fd_35c3929396ffae\":[\"6.7\",\"6.8\",\"5.6\"], \"fd_35c391fad19852.fd_35c392958474c8\":[\"6.6\",\"6.7\",\"5.5\"], \"fd_35c391fad19852.fd_35e950dcf929e6\":[\"0.1\",\"0.1\",\"0.1\"], \"fd_35c391fad19852.fd_35c39297a9cf56\":[\"6.6\",\"6.7\",\"5.5\"]}}";
		form.setFormValues(formValues);
		List<AttachmentForm> attForms = new ArrayList<AttachmentForm>();
		String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/static/"+oilPrice.getFileUrl();
		AttachmentForm attForm = new AttachmentForm();
		attForm.setFdKey("fd_35c3927c26cf2e");
		attForm.setFdFileName(oilPrice.getPriceText()+".jpg");
		AttachmentForm attForm01 = createAtt(path, attForm);
		attForms.add(attForm01);
		//HTTPSClient client = new HTTPSClient();
		form.getAttachmentForms().addAll(attForms);
		//String ss = client.PostOaApi(url, form);
		/*JSONObject jsonObject = JSONObject.parseObject(ss);
        String jsd = jsonObject.getString("addReviewResponse");
        JSONObject jsonObject1 = JSONObject.parseObject(jsd);
		String fdid = jsonObject1.getString("return");*/
		return null;
	}

}
